package com.zhx.servlet;

import com.zhx.bean.User;
import com.zhx.tool.JdbcConnection;
import javafx.application.Application;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.util.Map;

/**
 * @program: web-framework
 * @author: zhx
 * @create: 2021-03-18 21:59
 **/
public class LoginServlet extends HttpServlet {
    /**
     * @param req
     * @param resp 重写doPost方法，用来对post请求做处理
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //告诉服务器要用UTF-8的编码来解析
        req.setCharacterEncoding("UTF-8");
        //告诉页面，要用UTF-8的编码来解析
        resp.setCharacterEncoding("UTF-8");
        String username="";
        String password="";
        //判断是否有session
        User user1 = (User) req.getSession().getAttribute("user");
        if(user1!=null){
            //从session中获取
            username=user1.getUsername();
            password=user1.getPassword();
        }else{
            //获取从页面传过来的数据
            username = req.getParameter("username");
            password = req.getParameter("password");
        }
        //判断数据是否正确
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            //和数据库的数据进行比对
            User user = getUserfromdb(username, password);
            if (user != null) {//说明找到了
                //登陆成功，创建session
                createSession(req, user);
                req.getServletContext().getRequestDispatcher("/LoginSuccess.jsp").forward(req, resp);
            } else {//没有用户名或者密码错误
                req.setAttribute("error", "用户名或密码错误！");
                req.getServletContext().getRequestDispatcher("/Login.jsp").forward(req, resp);
            }
        } else {
            resp.sendRedirect(req.getContextPath()+"/Login.jsp");
        }
    }

    /**
     * @param req
     * @param resp 重写doGet方法，用来对get请求做处理
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 创建session
     */
    public HttpSession createSession(HttpServletRequest request, Object object) {
        User user = (User) object;
        HttpSession session = null;
        if (request.getSession().getAttribute("user") == null) {
            //如果没有sessino就创建一个session
            session = request.getSession(true);
            String JSESSIONID_VALUE = request.getSession().getId();
            ServletContext application = request.getServletContext();
            Map<String, String> online = (Map<String, String>) application.getAttribute("online");
            online.put(JSESSIONID_VALUE, user.getUsername());
            application.setAttribute("online", online);
            session.setAttribute("user", user);
        }
        return session;
    }

    /**
     * 输入username，password
     * 输出user对象
     * 从数据库中获取数据，返回对象
     */
    public User getUserfromdb(String username, String password) {
        User user = null;
        //1,获取连接数据库的对象
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcConnection.getconn();
            //2，获取操作数据库的对象
            statement = connection.prepareStatement("select * from USER WHERE username=? and password=?");
            statement.setString(1, username);
            statement.setString(2, password);
            //3，获取结果集
            resultSet = statement.executeQuery();//这个结果绝对不会返回一个null的
            if (resultSet.next()) {//从数据库中查到数据了
                user = new User();
                user.setUsername(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
            }
            //4,关闭数据库连接
            JdbcConnection.closeAll(resultSet, statement, connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
